package com.portal.back.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import com.opensymphony.xwork2.ActionContext;
import com.portal.back.service.ISysLinkService;
import com.portal.back.service.impl.SysLinkService;
import com.portal.base.web.BaseAction;
import com.portal.domain.SysLink;
import com.portal.util.common.CharacterUtil;

/**
 * @Title:友情链接Action
 * @Copyright: Copyright (c) 0.1
 * @author:鲁根成
 * @version: 1.0
 * @time: 2011-4-6
 * 
 */
@SuppressWarnings("serial")
public class SysLinkAction extends BaseAction {
	private ISysLinkService service;

	public SysLinkAction() {
		service = new SysLinkService();
	}

	private SysLink link;

	/**
	 * 新增友情链接
	 * 
	 * @return
	 */
	public String add() {
		link.setName(CharacterUtil.encode(link.getName()));
		link.setUrl(CharacterUtil.encode(link.getUrl()));
		link.setLogoUrl(CharacterUtil.encode(link.getLogoUrl()));
		boolean isFlag = service.addLink(link);
		if (isFlag) {
			response.setContentType("text/html");
			try {
				request.setCharacterEncoding("utf-8");
				response.setCharacterEncoding("utf-8");
				PrintWriter out = response.getWriter();
				String bath = request.getContextPath();
				out
						.println("<script>alert('保存成功');window.parent.location.href='"
								+ bath + "/link/getAllLink.shtml';</script>");

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			return null;
		} else
			return "error";

	}

	/**
	 * 查出所有的友情链接
	 * 
	 * @return
	 */
	public String getAllLink() {
		List<SysLink> list = service.getAllLink();
		ActionContext context = ActionContext.getContext();
		context.put("list", list);
		return "getLink";

	}

	/**
	 * 删除友情链接
	 * 
	 * @return
	 */
	public String deleteAllLink() {
		String deleteByIdString = request.getParameter("id");
		boolean isFlag = service.deleteById(deleteByIdString);
		response.setContentType("text/html;charset=gbk");
		PrintWriter out = null;
		if (isFlag)
			message = "删除成功";
		else
			message = "删除失败";
		StringBuffer sb = new StringBuffer("[");
		sb.append("{\"message\":\"" + message + "\"" + "}");
		sb.append("]");

		try {
			out = response.getWriter();
			out.println(sb.toString());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;

	}

	/**
	 * 查出某个友情链接
	 * 
	 * @return
	 */
	public String getSomeById() {
		String id = request.getParameter("id");
		SysLink link = service.getById(id);
		ActionContext context = ActionContext.getContext();
		context.put("link", link);
		return "somelink";
	}

	public SysLink getLink() {
		return link;
	}

	public void setLink(SysLink link) {
		this.link = link;
	}
}
